import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
// import { ElMessage } from "element-plus";
import { staticRoutes, allAsyncRoutes, anyRoutes } from "@/router/routes";
import { loginApi, logoutApi, getUserInfoApi } from "@/api/acl/login";
import type { RouteRecordRaw } from "vue-router";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";

function filterAsyncRoutes(allAsyncRoutes: RouteRecordRaw[], routes: string[]) {
  return allAsyncRoutes.filter((route) => {
    if (routes.includes(route.name as string)) {
      // 说明拥有访问权限, 保留
      // 如果有子路由（子菜单），也需要进行判断是否拥有访问权限
      if (route.children) {
        route.children = filterAsyncRoutes(route.children, routes);
      }
      return true;
    }
    // 没有访问权限，过滤
    return false;
  });
}

function addRoutes(routes: RouteRecordRaw[]) {
  routes.forEach((route) => {
    router.addRoute(route);
  });
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [],
    buttons: [],
    routes: [],
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      const { token } = await loginApi(username, password);
      this.token = token; // 存储在pinia中
      setToken(token); // 存储在localStorage中
    },
    // 登出
    async logout() {
      await logoutApi(); // 发送请求，退出登录
      this.reset(); // 清空本地数据
    },

    async getInfo() {
      const res = await getUserInfoApi(); // 获取用户数据
      this.name = res.name;
      this.avatar = res.avatar;
      this.buttons = res.buttons; // 按钮权限列表
      this.routes = res.routes; // 路由权限列表

      // 实现路由权限管理
      // 1. 过滤路由菜单。保留拥有访问权限的路由
      const routes = filterAsyncRoutes(cloneDeep(allAsyncRoutes), res.routes);
      // 2. 将路由添加到router中生效
      addRoutes([...routes, ...anyRoutes]); // 添加动态路由+任意路由

      this.menuRoutes = [...staticRoutes, ...routes]; // 左侧菜单：静态路由+动态路由
    },

    reset() {
      // 删除localStorage中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.$reset();
    },
  },
});
